﻿#include "HttpPost.h"

#include <QDebug>
#include <QEventLoop>
#include <QJsonDocument>
#include <QNetworkRequest>
#include <QTimer>
#include <QUrl>

#include "QFile"
#include "QJsonArray"
#include "QUrlQuery"

HttpPost::HttpPost(QObject *parent)
    : QObject(parent)
    , manager(new QNetworkAccessManager(this))
{
}

bool HttpPost::post(const QString &strUrl, const QString &strJsonFile)
{
    lastError.clear();

    QUrl url(strUrl);

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::UserAgentHeader,
                      "Codeforces API Client/1.0");
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);

    QEventLoop eventLoop;
    QTimer timer;

    timer.setSingleShot(true);
    QObject::connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);

    QNetworkReply *reply = manager->get(request);

    QObject::connect(reply, &QNetworkReply::finished, &eventLoop,
                     &QEventLoop::quit);

    timer.start(10000);

    eventLoop.exec();

    if (!timer.isActive())
    {
        lastError = "Request timeout";
        reply->abort();
        reply->deleteLater();
        return false;
    }
    timer.stop();

    if (reply->error() != QNetworkReply::NoError)
    {
        lastError = reply->errorString();
        reply->deleteLater();
        return false;
    }

    QByteArray responseData = reply->readAll();
    reply->deleteLater();

    if (0)
    {
        QFile file(strJsonFile);
        if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly))
        {
            qWarning() << "无法打开文件:" << file.errorString();
            return false;
        }

        file.write(responseData);
        file.close();
    }

    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        lastError = "JSON parse error: " + parseError.errorString();
        return false;
    }

    if (m_bAtcoder)
    {
        if (jsonDoc.isObject())
        {
            if (jsonDoc.isEmpty())
            {
                return false;
            }
        }
        else
        {
            QJsonArray jar = jsonDoc.array();
            if (jar.size() == 0)
            {
                //lastError = "Data is empty.";
                //return false;
            }
        }
    }
    else
    {
        if (!jsonDoc.isObject() || jsonDoc.isEmpty())
        {
            return false;
        }

        QJsonObject jsonObject = jsonDoc.object();
        if (jsonObject["status"].toString() != "OK")
        {
            lastError = "API error";
            return false;
        }
    }

    QFile file(strJsonFile);
    if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly))
    {
        qWarning() << "无法打开文件:" << file.errorString();
        return false;
    }

    file.write(jsonDoc.toJson());
    file.close();

    return true;
}

void HttpPost::setAtcoder(bool b) { m_bAtcoder = b; }

QString HttpPost::getLastError() const { return lastError; }